import math
from datetime import datetime
from typing import Any, List, Optional, TypeVar, Generic, Sequence

from fastapi import APIRouter, Depends, HTTPException, status, Query
from fastapi_pagination import Page
from fastapi_pagination.bases import AbstractParams, RawParams, AbstractPage
from fastapi_pagination.ext.sqlalchemy import paginate
from pydantic import BaseModel

from pydantic.types import UUID4
from sqlalchemy import or_
from sqlalchemy.orm import Session

from app import crud, models, schemas
from app.api import deps
from app.models.BroadcastPresets import BroadcastPresets
router = APIRouter()

@router.get("/search", summary="检索播报文案预设卡片")
async def search_broadcast_presets(
        search_key: Optional[str] = None,
        search_category: Optional[str] = None,
        start_date: Optional[datetime] = None,
        end_date: Optional[datetime] = None,
        db: Session = Depends(deps.get_db),
        page_size: int = Query(10, alias="page_size"),  # 每页显示多少条数据
        current_page: int = Query(1, alias="current_page")  # 当前页码
) -> Any:
    """
    通过关键字/日期/分类名 检索 播报文案预设卡片。
    """
    try:
        # query = db.query(PersonalizedVocabulary)
        query = db.query(BroadcastPresets)


        if search_key:
            query = query.filter(
                or_(
                    BroadcastPresets.title.ilike(f"%{search_key}%"),
                    BroadcastPresets.category_name.ilike(f"%{search_key}%"),
                    BroadcastPresets.content.ilike(f"%{search_key}%")
                )
            )

        if search_category:
            query = query.filter(BroadcastPresets.category_name == search_category)

        if start_date:
            query = query.filter(BroadcastPresets.updated_at >= start_date)

        if end_date:
            query = query.filter(BroadcastPresets.updated_at <= end_date)
        # 计算总记录数
        total = query.count()
        results = query.offset((current_page - 1) * page_size).limit(page_size).all()
        # results = paginate(query)
        items = []
        for result in results:
            updated_at = result.updated_at if result.updated_at else result.created_at
            result.updated_at = updated_at.strftime("%Y年%m月%d日 %H:%M:%S")
            result.created_at = result.created_at.strftime(
                "%Y年%m月%d日 %H:%M:%S")
            items.append({
                "id": result.id,
                "title": result.title,
                "category_name": result.category_name,
                "content": result.content,
                "created_at": result.created_at,
                "updated_at": result.updated_at,
            })
        final_result = {"total": total, "page":current_page, "size":page_size, "items": items}

        return final_result

        # return paginate(query)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
# @router.get("/", response_model=Page[schemas.BroadcastPresets], summary="检索播报文案预设卡片")
# async def read_broadcast_presets(
#     db: Session = Depends(deps.get_db),
#     # skip: int = 0,
#     # limit: int = 100,
#     current_user: models.User = Depends(deps.get_current_user),
# ) -> Any:
#     """
#     检索当前用户的播报文案预设卡片。管理员用户检索所有播报文案预设卡片。
#     """
#     try:
#         if current_user.is_admin:
#             broadcast_preset = crud.broadcast_presets.get_paginate(db)
#             # broadcast_presets = crud.broadcast_presets.get_multi(db, skip=skip, limit=limit)
#         else:
#             # broadcast_presets = crud.broadcast_presets.get_multi_by_user(
#             #     db, user=current_user, skip=skip, limit=limit
#             # )
#             broadcast_preset = crud.broadcast_presets.get_paginate_by_user(
#                 db, user=current_user
#             )
#
#         return broadcast_preset
#     except Exception as e:
#         raise HTTPException(status_code=500, detail=str(e))

@router.post("/", response_model=schemas.BroadcastPresets, summary="创建播报文案预设卡片")
async def create_broadcast_preset(
    *,
    db: Session = Depends(deps.get_db),
    broadcast_preset_in: schemas.BroadcastPresetsCreate,
    # current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    """
    创建新的播报文案预设卡片。
    """
    try:
        # updated_at = broadcast_preset_in.updated_at if broadcast_preset_in.updated_at else broadcast_preset_in.created_at
        # broadcast_preset_in.updated_at = updated_at
        broadcast_preset = crud.broadcast_presets.create(db=db, obj_in=broadcast_preset_in)
        # updated_at = broadcast_preset.updated_at if broadcast_preset.updated_at else broadcast_preset.created_at
        # broadcast_preset.updated_at = updated_at
        return broadcast_preset
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
#
# @router.post("/admin", response_model=schemas.BroadcastPresets, summary="创建播报文案预设卡片（管理员）")
# async def create_broadcast_preset_admin(
#     *,
#     db: Session = Depends(deps.get_db),
#     broadcast_preset_in: schemas.BroadcastPresetsCreate,
#     _: models.User = Depends(deps.get_current_admin_user),
#     user_id: UUID4,
# ) -> Any:
#     """
#     ADMIN: 为其他用户创建播报文案预设卡片。
#     """
#     try:
#         user = crud.user.get(db=db, id=user_id)
#         if not user:
#             raise HTTPException(
#                 status_code=status.HTTP_404_NOT_FOUND, detail="用户未找到"
#             )
#         broadcast_preset = crud.broadcast_presets.create_with_user(db=db, obj_in=broadcast_preset_in, user=user)
#         return broadcast_preset
#     except Exception as e:
#         raise HTTPException(status_code=500, detail=str(e))


@router.put("/{id}", response_model=schemas.BroadcastPresets, summary="更新播报文案预设卡片")
async def update_broadcast_preset(
    *,
    db: Session = Depends(deps.get_db),
    id: UUID4,
    broadcast_preset_in: schemas.BroadcastPresetsUpdate,
    # current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    """
    更新播报文案预设卡片。
    """
    try:
        broadcast_preset = crud.broadcast_presets.get(db=db, id=id)
        if not broadcast_preset:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND, detail="播报文案预设卡片未找到"
            )
        # if not current_user.is_admin and (broadcast_preset.user_id != current_user.id):
        #     raise HTTPException(
        #         status_code=status.HTTP_403_FORBIDDEN, detail="权限不足"
        #     )
        broadcast_preset = crud.broadcast_presets.update(db=db, db_obj=broadcast_preset, obj_in=broadcast_preset_in)
        return broadcast_preset
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# 添加新的关键字检索接口
# @router.get("/searchkey", response_model=Page[schemas.BroadcastPresets], summary="通过关键字检索播报文案预设")
# async def search_personalized_vocabulary(
#     keyword: str = Query(...),
#     db: Session = Depends(deps.get_db),
#     current_user: models.User = Depends(deps.get_current_user)
# ) -> Any:
#     """
#     通过关键字检索播报文案预设。管理员用户检索所有播报文案预设，普通用户只检索自己的播报文案预设。
#     """
#     try:
#     # print(keyword)
#         if current_user.is_admin:
#
#             # task_classification_libraries = crud.task_classification_library.get_by_keyword(db=db, keyword=keyword)
#             broadcast_preset = crud.broadcast_presets.get_key_paginate(
#                 db, keyword=keyword
#             )
#         else:
#             broadcast_preset = crud.broadcast_presets.get_key_paginate_by_user(
#                 db, user=current_user, keyword=keyword
#             )
#         return broadcast_preset
#     except Exception as e:
#         # 引发HTTP 500，表示请求无效
#         raise HTTPException(
#             status_code=500,
#             detail=str(e)
#         )

@router.get("/{id}", summary="获取播报文案预设卡片详情")
async def read_broadcast_preset(
    *,
    db: Session = Depends(deps.get_db),
    id: UUID4,
    # current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    """
    按 ID 获取播报文案预设卡片。
    """
    try:
        broadcast_preset = crud.broadcast_presets.get(db=db, id=id)
        if not broadcast_preset:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND, detail="播报文案预设卡片未找到"
            )
        # if not current_user.is_admin and (broadcast_preset.user_id != current_user.id):
        #     raise HTTPException(
        #         status_code=status.HTTP_403_FORBIDDEN, detail="权限不足"
        #     )

        if broadcast_preset:
            updated_at = broadcast_preset.updated_at if broadcast_preset.updated_at else broadcast_preset.created_at
            broadcast_preset.updated_at = updated_at.strftime("%Y年%m月%d日 %H:%M:%S")
            broadcast_preset.created_at = broadcast_preset.created_at.strftime("%Y年%m月%d日 %H:%M:%S")
        result = {}
        result["id"] = broadcast_preset.id
        result["category_name"] = broadcast_preset.category_name
        result["content"] = broadcast_preset.content
        result["created_at"] = broadcast_preset.created_at
        result["updated_at"] = broadcast_preset.updated_at
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{id}", response_model=schemas.BroadcastPresets, summary="删除播报文案预设卡片")
async def delete_broadcast_preset(
    *,
    db: Session = Depends(deps.get_db),
    id: UUID4,
    # current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    """
    按 ID 删除播报文案预设卡片。
    """
    try:
        broadcast_preset = crud.broadcast_presets.get(db=db, id=id)
        if not broadcast_preset:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND, detail="播报文案预设卡片未找到"
            )
        # if not current_user.is_admin and (broadcast_preset.user_id != current_user.id):
        #     raise HTTPException(
        #         status_code=status.HTTP_403_FORBIDDEN, detail="权限不足"
        #     )
        broadcast_preset = crud.broadcast_presets.remove(db, obj=broadcast_preset)
        return broadcast_preset
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# @router.get("/search_category/", response_model=Page[schemas.BroadcastPresets], summary="根据分类名称查询播报文案预设卡片")
# async def read_broadcast_presets_by_category(
#     *,
#     db: Session = Depends(deps.get_db),
#     category_name: str,
#     current_user: models.User = Depends(deps.get_current_user),
# ) -> Any:
#     """
#     根据分类名称查询播报文案预设卡片。
#     """
#     try:
#         broadcast_presets = crud.broadcast_presets.get_by_category_name(db=db, category_name=category_name)
#         return paginate(broadcast_presets)
#     except Exception as e:
#         raise HTTPException(status_code=500, detail=str(e))
#
# @router.get("/searchbydate/", response_model=Page[schemas.BroadcastPresets], summary="根据日期范围查询播报文案预设卡片")
# async def read_broadcast_presets_by_date_range(
#     *,
#     db: Session = Depends(deps.get_db),
#     start_date: datetime,
#     end_date: datetime,
#     current_user: models.User = Depends(deps.get_current_user),
# ) -> Any:
#     """
#     根据日期范围查询播报文案预设卡片。
#     """
#     try:
#         broadcast_presets = crud.broadcast_presets.get_by_date_range(db=db, start_date=start_date, end_date=end_date)
#         return paginate(broadcast_presets)
#     except Exception as e:
#         raise HTTPException(status_code=500, detail=str(e))

# @router.get("/unique_categories/", response_model=List[str], summary="获取播报文案预设分类名称的不重复列表")
# async def get_unique_categories(
#     db: Session = Depends(deps.get_db),
#     current_user: models.User = Depends(deps.get_current_user),
# ) -> List[str]:
#     """
#     获取分类名称的不重复列表。
#     """
#     try:
#         categories = crud.broadcast_presets.get_unique_categories(db=db)
#         return categories
#     except Exception as e:
#         raise HTTPException(status_code=500, detail=str(e))